import { create } from 'zustand';
import { User, LoginRequest, RegisterRequest } from '../types';
import apiService from '../services/api';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  
  // Actions
  login: (credentials: LoginRequest) => Promise<void>;
  register: (userData: RegisterRequest) => Promise<void>;
  logout: () => void;
  getCurrentUser: () => Promise<void>;
  updateUserProfile: (profileData: { email?: string; full_name?: string }) => Promise<void>;
  clearError: () => void;
  setLoading: (loading: boolean) => void;
  initializeAuth: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()((set, get) => ({
  user: null,
  token: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,

  login: async (credentials: LoginRequest) => {
    try {
      set({ isLoading: true, error: null });
      
      const response = await apiService.login(credentials);
      
      // 存储token到localStorage
      localStorage.setItem('auth-token', response.access_token);
      
      set({
        user: response.user,
        token: response.access_token,
        isAuthenticated: true,
        isLoading: false,
        error: null,
      });
    } catch (error: any) {
      set({
        isLoading: false,
        error: error.message || '登录失败',
      });
      throw error;
    }
  },

  register: async (userData: RegisterRequest) => {
    try {
      set({ isLoading: true, error: null });
      
      await apiService.register(userData);
      
      // 注册成功后自动登录
      await get().login({
        username: userData.username,
        password: userData.password,
      });
    } catch (error: any) {
      set({
        isLoading: false,
        error: error.message || '注册失败',
      });
      throw error;
    }
  },

  logout: () => {
    localStorage.removeItem('auth-token');
    set({
      user: null,
      token: null,
      isAuthenticated: false,
      error: null,
    });
  },

  getCurrentUser: async () => {
    try {
      const token = localStorage.getItem('auth-token');
      if (!token) {
        return;
      }

      set({ isLoading: true });
      
      const user = await apiService.getCurrentUser();
      
      set({
        user,
        token,
        isAuthenticated: true,
        isLoading: false,
        error: null,
      });
    } catch (error: any) {
      // Token可能已过期，清除认证状态
      localStorage.removeItem('auth-token');
      set({
        user: null,
        token: null,
        isAuthenticated: false,
        isLoading: false,
        error: null,
      });
    }
  },

  updateUserProfile: async (profileData: { email?: string; full_name?: string }) => {
    try {
      set({ isLoading: true, error: null });
      
      const updatedUser = await apiService.updateUserProfile(profileData);
      
      set({
        user: updatedUser,
        isLoading: false,
        error: null,
      });
    } catch (error: any) {
      set({
        isLoading: false,
        error: error.message || '更新失败',
      });
      throw error;
    }
  },

  clearError: () => {
    set({ error: null });
  },

  setLoading: (loading: boolean) => {
    set({ isLoading: loading });
  },

  initializeAuth: async () => {
    const token = localStorage.getItem('auth-token');
    if (token) {
      await get().getCurrentUser();
    }
  },
})); 